package com.stmt.stmtdesktop;

import com.stmt.stmtdesktop.udp.DeviceEnum;
import com.stmt.stmtdesktop.udp.DeviceEnum.DeviceInstruct;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;

/**
 * $0123456789ABCDEF<001><1001><123456789012345><100>
 *
 * @author liangbo
 */

public class DefaultServerRequest {

  //$1-6<?><?><?><?><?><?>
  private final String body;
  private final List<String> params;

  private final TcpIpType tcpIpType;

  private final boolean isResponse;

  private final DeviceEnum.DeviceInstruct instruction;

  public DefaultServerRequest(String body,
      TcpIpType tcpIpType) {
    this.tcpIpType = tcpIpType;
    this.body = body;
    var macno = body.substring(1, body.indexOf('<'));
    params = new ArrayList<>();
    params.add(macno);

    Pattern p2 = Pattern.compile("(?<=<)[^>]+");
    Matcher m2 = p2.matcher(body);
    while (m2.find()) {
      params.add(m2.group());
    }
    this.instruction = Arrays.stream(DeviceInstruct.values())
        .filter(it -> Objects.equals(it.getCode(), params.get(2)))
        .findAny()
        .orElse(null);
    if (this.instruction != null) {
      if (params.size() <= 3) {
        isResponse = false;
      } else {
        isResponse = Objects.equals(params.get(3), "OK") || Objects.equals(params.get(3), "ER");
      }
    } else {
      isResponse = true;
    }
  }

  public enum TcpIpType {
    /**
     * 协议类型
     */
    TCP(1), UDP(0);
    private final Integer code;

    TcpIpType(Integer code) {
      this.code = code;
    }

    public Integer getCode() {
      return code;
    }
  }


  public String body() {
    return body;
  }

  public List<String> queryParams() {
    return params;
  }

  public String getMacno() {
    return params.get(0);
  }

  public String getFrame() {
    return params.get(1);
  }


  public String getParam(int index) {
    return params.get(index);
  }

  public DeviceInstruct getInstruction() {
    return instruction;
  }

  public TcpIpType getTcpIpType() {
    return tcpIpType;
  }

  public boolean isResponse() {
    return isResponse;
  }
}
